python paramiko 远程调用 常见问题总结 您所在的位置:网站首页 got class python paramiko 远程调用 常见问题总结

python paramiko 远程调用 常见问题总结

2024-01-20 21:21| 来源: 网络整理| 查看: 265

1 def u(s, encoding="utf8"): 2 """cast bytes or unicode to unicode""" 3 if isinstance(s, bytes): 4 try: 5 return s.decode(encoding) 6 except UnicodeDecodeError: 7 return s.decode('ISO-8859-1') 8 elif isinstance(s, str): 9 return s 10 else: 11 raise TypeError("Expected unicode or bytes, got {!r}".format(s))

 

问题6: ssh_client.exec_command执行很长时间卡住,没有任何输出

解决方法:这可能是因为执行的命令返回的输出内容很大,导致无法及时打印。解决方法可以使用channel轮回查询的方式,代码参考如下:

1 import sys 2 import time 3 import select 4 import paramiko 5 6 host = 'test.example.com' 7 i = 1 8 9 # 10 # Try to connect to the host. 11 # Retry a few times if it fails. 12 # 13 while True: 14 print "Trying to connect to %s (%i/30)" % (host, i) 15 16 try: 17 ssh = paramiko.SSHClient() 18 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 19 ssh.connect(host) 20 print "Connected to %s" % host 21 break 22 except paramiko.AuthenticationException: 23 print "Authentication failed when connecting to %s" % host 24 sys.exit(1) 25 except: 26 print "Could not SSH to %s, waiting for it to start" % host 27 i += 1 28 time.sleep(2) 29 30 # If we could not connect within time limit 31 if i == 30: 32 print "Could not connect to %s. Giving up" % host 33 sys.exit(1) 34 35 # Send the command (non-blocking) 36 stdin, stdout, stderr = ssh.exec_command("my_long_command --arg 1 --arg 2") 37 38 # Wait for the command to terminate 39 while not stdout.channel.exit_status_ready(): 40 # Only print data if there is data to read in the channel 41 if stdout.channel.recv_ready(): 42 rl, wl, xl = select.select([stdout.channel], [], [], 0.0) 43 if len(rl) > 0: 44 # Print data from stdout 45 print stdout.channel.recv(1024), 46 47 # 48 # Disconnect from the host 49 # 50 print "Command done, closing SSH connection" 51 ssh.close()

该方案转自:http://sebastiandahlgren.se/2012/10/11/using-paramiko-to-send-ssh-commands/



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有